package com.linkai.多线程._02_Callable;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @Description: 线程创建方式三，实现 callable 接口
 * @Author: 林凯
 * @Date: 2021/10/19 18:29
 */
public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;    // 保存的文件名

    public TestCallable(String url, String name) {
        this.url = url;
        this.name = name;
    }

    // 下载图片线程的执行体
    public Boolean call() throws Exception {
        WebDownload webDownload = new WebDownload();
        webDownload.downloader(url, name);
        System.out.println("success" + name);
        return null;
    }



    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://public-cdn.mokahr.com/54fc4e3d-b42b-461a-9250-f3695e9bce98.jpg", "1.jpg");
        TestCallable t2 = new TestCallable("https://public-cdn.mokahr.com/54fc4e3d-b42b-461a-9250-f3695e9bce98.jpg", "2.jpg");
        TestCallable t3 = new TestCallable("https://public-cdn.mokahr.com/54fc4e3d-b42b-461a-9250-f3695e9bce98.jpg", "3.jpg");

        // 1. 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);

        // 2. 提交执行
        Future<Boolean> r1 = service.submit(t1);
        Future<Boolean> r2 = service.submit(t2);
        Future<Boolean> r3 = service.submit(t3);

        System.out.println(r1);
        System.out.println(r2);
        System.out.println(r3);

        // 3. 获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        // 4. 关闭服务
        service.shutdownNow();
    }
}

// 下载器
class WebDownload {

    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}